package com.threeti.mecool.framework.util;

import java.util.Collection;

import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnitUtil;

/** 
 * This helper class should be worked under transaction boundary
 * 
 * @author Jay Meng
 */
public abstract class JpaUtil {

  public static Collection<?> forceInitializeCollection(Collection<?> collection, EntityManagerFactory emFactory) {
    if (collection == null) {
      return null;
    }
    PersistenceUnitUtil unitUtil = emFactory.getPersistenceUnitUtil();
    
    if (!unitUtil.isLoaded(collection)) {//TODO jay:only working under specified situation 
      collection.iterator().hasNext();
    }
    return collection;
  }

  public static Collection<?> forceInitializeCollection(Object collectionHolderObj, String collectionIdentifier, Collection<?> collection, EntityManagerFactory emFactory) {
    if (collectionHolderObj == null || collection == null) {
      return null;
    }
    PersistenceUnitUtil unitUtil = emFactory.getPersistenceUnitUtil();
    if (!unitUtil.isLoaded(collectionHolderObj, collectionIdentifier)) {//jay:some times unitUtil.isLoaded(collection obj) is not worked as expected,under transaction mode aspectj,whenever native projects is not compiled with aspectj library under specified aspectj classpath
      // works with Hibernate EM 3.6.1-SNAPSHOT
      collection.iterator().hasNext();
    }
    return collection;
  }
}
